<?php
namespace Swork\Helper;

/**
 * TCP处理器
 * Class TcpHelper
 * @package Swork\Helper
 */
class TcpHelper
{
    /**
     * 按照内部定义的格式获取内容
     * @param string $data 传输内容
     * @return array | boolean
     */
    public static function getContent(string $data)
    {
        //传输内容长度
        $len = strlen($data);
        if ($len < 3)
        {
            return false;
        }

        //提取命令头
        $cmd_L1 = intval(substr($data, 0, 1));
        if ($cmd_L1 == 0)
        {
            return false;
        }
        $cmd_L2 = intval(substr($data, 1, $cmd_L1));
        if ($cmd_L2 == 0)
        {
            return false;
        }
        $cmd_CT = substr($data, 1 + $cmd_L1, $cmd_L2);
        if ($cmd_CT == '')
        {
            return false;
        }

        //默认返回内容
        $rel = [
            $cmd_CT
        ];

        //提取命令内容
        $cnt_L1 = intval(substr($data, 1 + $cmd_L1 + $cmd_L2, 1));
        if ($cnt_L1 == 0)
        {
            return $rel;
        }
        $cnt_L2 = intval(substr($data, 1 + $cmd_L1 + $cmd_L2 + 1, $cnt_L1));
        if ($cnt_L2 == 0)
        {
            return $rel;
        }
        $cnt_CT = substr($data, 1 + $cmd_L1 + $cmd_L2 + 1 + $cnt_L1, $cnt_L2);
        if ($cnt_CT == '')
        {
            return $rel;
        }
        $rel[] = $cnt_CT;

        //最终命令内容
        return $rel;
    }

    /**
     * 按照内部定义的格式组装内容
     * @param string $cmd 命令头
     * @param string $content 命令内容
     * @return array | boolean
     */
    public static function assemblyContent(string $cmd, string $content)
    {
        //传输内容长度
        $len1 = strlen($cmd);
        $len2 = strlen($content);
        if ($len1 == 0)
        {
            return false;
        }

        //组装命令头
        $cmd_L1 = strlen(strval($len1));
        $cmd_CT = strval($cmd_L1) . strval($len1) . $cmd;

        //组装命令内容
        $cnt_CT = '';
        if ($len2 > 0)
        {
            $cnt_L1 = strlen(strval($len2));
            $cnt_CT = strval($cnt_L1) . strval($len2) . $content;
        }

        //最终命令内容
        return $cmd_CT . $cnt_CT;
    }
}
